package com.thinkgem.jeesite.modules.spider.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thinkgem.jeesite.modules.spider.entity.SpiderLog;
import com.thinkgem.jeesite.modules.spider.service.SpiderLogService;

import us.codecraft.webmagic.Spider;

public class SpiderMonitorTask extends Thread {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	Spider spider;
	private SpiderLogService logService;
	boolean isKeepRunning = true;
	

	public SpiderMonitorTask(Spider spider, SpiderLogService logService) {
		super();
		this.spider = spider;
		this.logService = logService;
	}

	@Override
	public void run() {
		while (isKeepRunning) {
			logger.debug("=======Monitor Task=========");
			try {
				Thread.sleep(60 * 1000);
			} catch (InterruptedException e) {
				logService.save(new SpiderLog(this.getClass().toString(), SpiderConstants.LOG_LEVEL_ERROR,
						e.getLocalizedMessage()));
				e.printStackTrace();
			}
			if (spider != null && spider.getThreadAlive() == 0) {
				try {
					spider.stop();
					spider.start();
				} catch (Exception e) {
					logService.save(new SpiderLog(this.getClass().toString(), SpiderConstants.LOG_LEVEL_ERROR,
							e.getLocalizedMessage()));
					e.printStackTrace();
				}
			} else if (spider == null) {
				isKeepRunning = false;
			}
		}
	}
}
